import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'

// 发票信息
const announcementData = ref([])

// 分页配置
const announcementPagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 筛选条件
const announcementFilters = reactive({
  dateRange: 'all',
  search: ''
})

// 从Chrome存储中获取公告信息
const fetchAnnouncementData = async () => {
  return new Promise<any[]>((resolve) => {
    chrome.storage.local.get(['capturedRequests'], (result) => {
      const allRequests = Array.isArray(result.capturedRequests) ? result.capturedRequests : []
      
      // 筛选出公告信息（根据URL或数据类型）
      const announcementRequests = allRequests.filter(request => {
        // 根据拦截规则匹配公告信息
        return request.url && (
          request.url.includes('notice') || 
          request.url.includes('announcement') ||
          (request.dataType && request.dataType === 'announcement')
        )
      })
      
      // 处理数据格式
      const formattedData = announcementRequests.map((request: any, index) => {
        // 提取数据预览
        let preview = '{}'
        try {
          if (request.response) {
            preview = JSON.stringify(request.response, null, 2)
          } else if (request.requestBody) {
            preview = JSON.stringify(request.requestBody, null, 2)
          }
        } catch (e) {
          preview = '{}'
        }
        
        // 截取预览内容
        if (preview.length > 100) {
          preview = preview.substring(0, 100) + '...'
        }
        
        // 确定状态
        let status = '未读'
        if (request.synced) {
          status = '已同步'
        } else if (request.read) {
          status = '已读'
        }
        
        return {
          id: request.id || index + 1,
          date: request.timestamp ? new Date(request.timestamp).toLocaleString() : new Date().toLocaleString(),
          source: request.url || '未知来源',
          preview: preview,
          status: status
        }
      })
      
      resolve(formattedData)
    })
  })
}

// 渲染公告表格
const renderAnnouncementsTable = async () => {
  try {
    const data: any[] = await fetchAnnouncementData()
    announcementPagination.total = data.length
    
    // 分页处理
    const start = (announcementPagination.currentPage - 1) * announcementPagination.pageSize
    const end = start + announcementPagination.pageSize
    announcementData.value = data.slice(start, end)
  } catch (error) {
    console.error('获取公告信息失败:', error)
    ElMessage.error('获取公告信息失败')
  }
}

// 公告分页处理
const handleAnnouncementPageChange = (page) => {
  announcementPagination.currentPage = page
  renderAnnouncementsTable()
}

// 单条同步公告
const syncSingleAnnouncement = (row) => {
  ElMessage.success(`发票信息(ID: ${row.id})同步成功`)
}

// 删除公告
const deleteAnnouncement = (row) => {
  ElMessageBox.confirm(`确定要删除发票信息(ID: ${row.id})吗？`, '删除数据', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    ElMessage.success('删除成功')
  }).catch(() => {
    ElMessage.info('已取消删除')
  })
}

// 组件挂载时获取数据
onMounted(() => {
  renderAnnouncementsTable()
})

export function useAnnouncementData() {
  return {
    announcementData,
    announcementPagination,
    announcementFilters,
    renderAnnouncementsTable,
    handleAnnouncementPageChange,
    syncSingleAnnouncement,
    deleteAnnouncement
  }
}